/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Source;

/**
 *
 * @author jawi
 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ConexionDB {

    private String url = "jdbc:postgresql://localhost/guatebay";
    private String usuario = "postgres";
    private String password = "123";
    private Connection connection = null;

    public ConexionDB() {
        abrirConexion();
    }

    public Connection getConnection() {
        return connection;
    }

    public ResultSet getResultSet(String query) {
        Statement st = null;
        ResultSet rs = null;
        if (connection != null) {
            try {
                st = connection.createStatement();
                rs = st.executeQuery(query);
                return rs;
            } catch (SQLException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
                try {
                    if (rs != null) {
                        rs.close();
                    }
                    if (st != null) {
                        st.close();
                    }
                } catch (SQLException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
                }
            }
        }
        return null;
    }

    public void executeQuery(String query) {

        Statement st = null;
        if (connection != null) {
            try {
                st = connection.createStatement();
                st.executeUpdate(query);
            } catch (SQLException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);

            }
        }
    }

    public final void abrirConexion() {
        if (connection == null) {
            try {
                connection = DriverManager.getConnection(url, usuario, password);
            } catch (SQLException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void cerrarConexion() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
                connection = null;
            }
        } catch (SQLException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        }
    }
}